package com.eascs.web.o2o.scheduler.service;

import javax.inject.Inject;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.o2o.scheduler.dao.WorkflowDao;
import com.eascs.web.o2o.scheduler.util.Constant;

@Service
public class WorkflowService {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Inject
	WorkflowDao workflowDao;

	public <T> void loadData(String sql, Class<T> requiredType) {
		int index = 0;
		while (index >= 0) {
			SqlPageQuery<T> sqlPageQuery = new SqlPageQuery<>(requiredType, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<T> pageResult = this.workflowDao.findDataWithPage(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				T obj = pageResult.getData().get(i);
				try {
					boolean flag=workflowDao.updateEntity(obj);
					if(!flag){
						workflowDao.saveEntity(obj);
					}
				} catch (Exception e) {
					logger.error("数据库异常", e);
				}
			}
			if (pageResult.getPageTotal() > index + 1) {
				index++;
			} else {
				index = -1;
			}
		}

	}
	
	/**更新或者插入表部分数据
	 * @param sql 查询sql语句
	 * @param delSql 删除sql语句
	 * @param exeSql 执行更新或者添加的sql语句
	 */
	public void loadPartPartData(String sql, String delSql, String exeSql,String findEntitySql) {
		int index = 0;
		int total = 0;
		while (index >= 0) {
			SqlPageQuery <Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, sql);
			PageResult<Object[]> pageResult = this.workflowDao.findDataWithPage(sqlPageQuery);
			if (pageResult.getReturnDataSize() == 0)
				return;
			Integer count = pageResult.getDbRowCount();
			if (index == 0 && count > 0) {
				if (!"".equals(delSql)) {
					// 有数据先清空该表数据
					workflowDao.deleteEntity(delSql);
				}
			}
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] objs = pageResult.getData().get(i);

				logger.info("total:{},{}", ++total, objs);
				try {
				Integer flag=workflowDao.countMysql(findEntitySql,objs[1], objs[0]);
				  if(flag==0){
					workflowDao.excuteSql(exeSql, objs[0], objs[1]);
				  }
				} catch (DataIntegrityViolationException e) {
					logger.error("主键", objs[0]);
					logger.error("数据库异常", e);

				}
			}

			if (pageResult.getPageTotal() > index+1) {
				index++;
			} else {
				index = -1;
			}
		}

	}
	
	 
	

   /**
 * @插入 sql
 */
public void excute(String sql,Object... params){
		
	 workflowDao.excuteSql(sql,params);;
		
	}
}
